package com.kfm.login.interceptor;

import com.kfm.login.ex.JwtException;
import com.kfm.login.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (Constant.EXCLUDE_PATH.contains(requestURI)){
            return true;
        }
        String header = request.getHeader("token");
        if (header != null){
            Object o = redisTemplate.opsForValue().get(Constant.USER_PRE + header);
            if (o != null){
                return true;
            }
        }

        throw new JwtException("请先登录");

        // 判断是否已登录
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            String token = null;
//            for (Cookie cookie : cookies) {
//                if (Constant.TOKEN_KEY.equals(cookie.getName())) {
//                    token = cookie.getValue();
//                    Object o = redisTemplate.opsForValue().get(Constant.USER_PRE + token);
//                    if (o != null){
//                        return true;
//                    }
//                }
//            }
//        }
//        response.sendRedirect("/403");
    }
}
